<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      width="80%"
      align-center
      :show-close="false"
      @close="handleClose"
      draggable
    >
      <template #header="{ close }">
        <div class="dialog-header flex justify-between items-center">
          <div>{{ title }}</div>
          <el-icon class="el-icon--left cursor-pointer" @click="close"
            ><CircleCloseFilled color="#fff"
          /></el-icon>
        </div>
      </template>
      <!-- 基本信息 -->
      <div class="bg-white mt-[10px]">
        <BaseHead>基本信息</BaseHead>
        <div class="p-[10px]">
          <el-form :model="editForm" :rules="rules" label-width="130px" ref="editFormRef">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="评审方案名称" prop="name">
                  <el-input
                    placeholder="评审方案名称"
                    clearable
                    v-model="editForm.name"
                    style="width: 40%"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="满分" prop="fullMark">
                  <el-input clearable style="width: 40%" v-model="editForm.fullMark">
                    <template #append>（分）</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <!-- 评审标准 -->
      <div class="bg-white mt-[10px]">
        <BaseHead style="border-bottom: 0">
          评审标准 <el-button @click="handleAdd">添加标准</el-button></BaseHead
        >
        <el-table :data="standardList" class="w-full" border>
          <el-table-column label="一级标准">
            <template #default="{ row }">
              <div class="flex items-center">
                <span class="no-empty-icon">*</span>
                <el-input clearable v-model="row.lv1name"></el-input>
                <el-button link type="primary" @click="handleAddSecond(row)"
                  >添加二级标准</el-button
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column label="二级标准">
            <template #default="{ row }">
              <div class="flex items-center">
                <span class="no-empty-icon">*</span>
                <div class="w-full">
                  <el-input
                    clearable
                    v-for="(item, index) in row.lv2"
                    v-model="item.lv2name"
                    :key="index"
                    class="py-[2px]"
                  ></el-input>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="分数" width="150">
            <template #default="{ row }">
              <div class="flex items-center">
                <span class="no-empty-icon">*</span>
                <div class="w-full">
                  <el-input
                    clearable
                    v-for="(item, index) in row.lv2"
                    v-model="item.lv2mark"
                    :key="index"
                    class="py-[2px]"
                  ></el-input>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="120" align="center">
            <template #default="{ row, $index }">
              <div v-for="(item, index) in row.lv2" :key="index" class="py-[5px]">
                <el-button type="primary" size="small" plain @click="handelDel(row, $index, index)">
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <div class="operate-btns">
            <el-button type="primary" @click="save">保存</el-button>
            <el-button type="primary" @click="dialogVisible = false">关闭</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import BaseHead from "@/views/project/components/BaseHead.vue";
import { isNum } from "@/utils/validate";
import { editRecords, recordsDetail } from "@/api/project/xj/psfasz";
import _ from "lodash";
import { ElMessage } from "element-plus";
import { assignObj } from "@/utils/main";
const dialogVisible = ref(false);
const editFormRef = ref();
const operateId = ref(null);
const detailData = ref(null);
const title = computed(() => {
  return operateId.value ? "评审方案编辑" : "评审方案新增";
});
//基本信息表单
const editForm = reactive({
  name: "",
  fullMark: "",
});
//表单验证规则
const validateNum = (rule, value, callback) => {
  if (!isNum(value)) {
    callback(new Error("总分格式不正确!"));
  } else {
    callback();
  }
};
const rules = reactive({
  name: [
    {
      required: true,
      message: "评审方案名称必填",
    },
  ],
  fullMark: [
    {
      required: true,
      message: "总分必填",
    },
    { validator: validateNum, trigger: "blur" },
  ],
});
// 一级标准
const standardItem = {
  lv1name: "",
  lv1mark: "",
  lv2: [
    {
      lv2name: "",
      lv2mark: "",
    },
  ],
};
//二级标准
const secondStandardItem = {
  lv2name: "",
  lv2mark: "",
};
const standardList = ref([]);
//获取数据详情
const getDetail = async () => {
  const params = {
    id: operateId.value,
  };
  try {
    const res = await recordsDetail(params);
    detailData.value = res.data;
  } catch (error) {
    console.log(error);
  }
};
// 新增
const add = async () => {
  operateId.value = null;
  dialogVisible.value = true;
  //新增时默认添加一行标准
  standardList.value.push(_.cloneDeep(standardItem));
};
// 编辑
const edit = async (id) => {
  operateId.value = id;
  dialogVisible.value = true;
  await getDetail();
  nextTick(() => {
    assignObj(editForm, detailData.value);
    standardList.value = detailData.value.items;
  });
};
defineExpose({ add, edit });
//点击添加标准
const handleAdd = () => {
  standardList.value.push(_.cloneDeep(standardItem));
};
//点击添加二级标准
const handleAddSecond = (row) => {
  row.lv2.push(Object.assign({}, secondStandardItem));
};
//点击删除评审标准
const handelDel = (row, rowIndex, childIndex) => {
  //一级标准数量大于1
  if (standardList.value.length > 1) {
    if (row.lv2.length > 1) {
      row.lv2.splice(childIndex, 1);
    } else {
      standardList.value.splice(rowIndex, 1);
    }
  } else {
    if (row.lv2.length > 1) {
      row.lv2.splice(childIndex, 1);
    } else {
      ElMessage({
        message: "评审标准不能为空！",
        type: "error",
      });
    }
  }
};
const emit = defineEmits(["save-success"]);
//点击保存
const save = () => {
  try {
    editFormRef.value?.validate(async (valid) => {
      if (valid) {
        //校验各项是否都已填写
        let nullFlag = true;
        outer: for (let i = 0; i < standardList.value.length; i++) {
          if (standardList.value[i]["lv1name"].trim() == "") {
            nullFlag = false;
            break;
          }
          let childItems = standardList.value[i]["lv2"];
          for (let j = 0; j < childItems.length; j++) {
            if (childItems[j]["lv2name"].trim() == "" || childItems[j]["lv2mark"].trim() == "") {
              nullFlag = false;
              break outer;
            }
          }
        }
        if (!nullFlag) {
          ElMessage({
            message: "请检查评审标准各项数据是否全部填写！",
            type: "error",
          });
          return;
        }
        //校验分数是否符合要求
        let numFlag = true;
        outerLoop: for (let i = 0; i < standardList.value.length; i++) {
          for (let j = 0; j < standardList.value[i]["lv2"].length; j++) {
            let score = standardList.value[i]["lv2"][j].lv2mark;
            if (!isNum(score)) {
              numFlag = false;
              break outerLoop;
            }
          }
        }
        if (!numFlag) {
          ElMessage({
            message: "请检查各项分数是否为正数！",
            type: "error",
          });
          return;
        }
        //设置一级标准的分数 将一级标准下的二级标准分数累加
        for (let i = 0; i < standardList.value.length; i++) {
          standardList.value[i].lv1mark = 0;
          for (let j = 0; j < standardList.value[i]["lv2"].length; j++) {
            let score = parseFloat(standardList.value[i]["lv2"][j].lv2mark);
            standardList.value[i].lv1mark += score;
          }
        }
        //校验各项一级标准的分数加起来是否等于满数
        let totalScore = 0;
        for (let i = 0; i < standardList.value.length; i++) {
          totalScore += standardList.value[i].lv1mark;
        }
        if (totalScore != editForm.fullMark) {
          ElMessage({
            message: "评审标准总分与满分不相等！",
            type: "error",
          });
          return;
        }
        let params = {
          ...editForm,
          items: standardList.value,
        };
        if (operateId.value) {
          params.id = operateId.value;
        }
        const res = await editRecords(params);
        if (res.code === 200) {
          ElMessage({
            message: "操作成功！",
            type: "success",
          });
          dialogVisible.value = false;
          emit("save-success");
        }
      }
    });
  } catch (error) {
    console.log(error);
  }
};
//关闭弹窗
const handleClose = () => {
  //重置基本信息表单数据和评审标准信息数据
  editFormRef.value.resetFields();
  standardList.value = [];
};
</script>

<style scoped lang="scss">
@import url("@/views/project/index.scss");
</style>
